package com.jsj.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jsj.model.User;

@WebFilter(urlPatterns=("/*"))
public class AuthorityFiltet implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//获取已经登录用户信息
		HttpSession session=((HttpServletRequest)request).getSession();
		User loginUser=(User)session.getAttribute("loginInfo");
		//requestPath可以获取请求的路径
		String requestPath=((HttpServletRequest)request).getServletPath();
		System.out.println("requestPath="+requestPath);
		if(requestPath.endsWith("index")
				|| requestPath.contains("login")
				|| loginUser!=null && loginUser.getRoleId()==1 && requestPath.contains("user")) {
			chain.doFilter(request,response);
		}else {
			RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		

	}

}
